import { assert, Asset, resources } from 'cc';
import { PathUtils } from '../utils';

/*
 * @Author: byAcya xiaoxianbin@4399inc.com
 * @Date: 2025-02-11 14:39:01
 * @LastEditors: byAcya xiaoxianbin@4399inc.com
 * @LastEditTime: 2025-02-21 10:39:50
 * @FilePath: \CocosFramework\assets\script\core\res\ResMgr.ts
 * @Description: 资源管理
 */
//count 引用次数  complete 是否已经加载完成
type RState = { count: number; complete: boolean };

export interface IResMgr {
    loadFile(path: string): Promise<Asset>;
}

export class ResMgr implements IResMgr {
    private states: Map<string, RState> = new Map();

    async loadFile(path: string): Promise<Asset> {
        return new Promise<Asset>((resolve, reject) => {
            if (!PathUtils.getInstance().existFile(path)) return reject();
            const state = this.getState(path, true);
            if (state.complete) {
                state.count++;
                return resolve(resources.get(path));
            }
            resources.load(path, (err: Error, asset: Asset) => {
                if (err) return reject(err);
                state.complete = true;
                state.count++;
                return resolve(asset);
            });
        });
    }

    releaseFile(path: string): void {
        const state = this.getState(path);
        if (state && state.count > 0) {
            if (--state.count == 0) {
                resources.release(path);
                this.states.delete(path);
            }
        }
    }

    private getState(key: string, create?: boolean): RState {
        let state = this.states.get(key);
        if (create && !state) {
            state = { count: 0, complete: false };
            this.states.set(key, state);
        }
        return state;
    }
}
